package com.exartisan.thanhdoanhn;

import java.util.ArrayList;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.exartisan.adapter.PostAdapter;
import com.exartisan.bean.Post;
import com.exartisan.network.NetworkUtility;
import com.exartisan.network.NewNetworkUtility;
import com.exartisan.network.NewParamBuilder;
import com.exartisan.network.NewResponseTranslater;
import com.exartisan.network.NewRestConnector;
import com.exartisan.network.RestConnector;
import com.exartisan.util.DataHolder;
import com.exartisan.util.Util;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.PauseOnScrollListener;

public class FragmentBlog extends SherlockFragment {
	private ArrayList<Post> posts;
	private ListView lvNormal;
	View footer;
	PostAdapter adapter;

	ProgressBar prBar;
	Button btnRetry;
	boolean isLoading;
	boolean isLastPage;
	int pageCount;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.activity_event_content,
				container, false);
		lvNormal = (ListView) rootView.findViewById(R.id.lvNormal);
		prBar = (ProgressBar) rootView.findViewById(R.id.pro_blog);
		btnRetry = (Button) rootView.findViewById(R.id.btnRetryBlog);

		footer = inflater.inflate(R.layout.row_load_more, lvNormal, false);

		lvNormal.addFooterView(footer);

		lvNormal.setOnScrollListener(new PauseOnScrollListener(ImageLoader
				.getInstance(), true, true, new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if (visibleItemCount + firstVisibleItem == totalItemCount
						&& totalItemCount != 0) {
					if (posts == null) return;
					if (!isLoading && !isLastPage) {
						loadMore();
					}
				}
			}
		}));

		btnRetry.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				getData();
			}
		});

		if (posts == null){
			pageCount = 1;
        	isLastPage = false;
        	isLoading = false;
        	
			getData();
		}
		else
			setUpView();
		return rootView;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		
		if (posts != null) for (Post post : posts) {
			if (post==DataHolder.getPost()) post.setViews(post.getViews() + 1);
		}
		
		if (adapter != null) {
			adapter.flushLikeCmtCount();
			adapter.notifyDataSetChanged();
		}
		
	}

	private void setUpView() {
		btnRetry.setVisibility(View.GONE);
		prBar.setVisibility(View.GONE);
		lvNormal.setVisibility(View.VISIBLE);
		
		adapter = new PostAdapter(getSherlockActivity(), posts);

		lvNormal.setAdapter(adapter);
	}

	private void getData() {
		if (NetworkUtility.checkNetworkState(getSherlockActivity())) {
			btnRetry.setVisibility(View.GONE);
			prBar.setVisibility(View.VISIBLE);
			lvNormal.setVisibility(View.GONE);

			NewRestConnector.post("", NewParamBuilder
					.BuildParams(NewParamBuilder.BuildPostData(1)),
					new AsyncHttpResponseHandler() {
						@Override
						public void onSuccess(int arg0, String response) {
							if (response == null) {
								btnRetry.setVisibility(View.VISIBLE);
								prBar.setVisibility(View.GONE);
								lvNormal.setVisibility(View.GONE);
								return;
							}
							super.onSuccess(arg0, response);
							if (NewResponseTranslater.checkSuccess(response)&&getSherlockActivity()!=null) {
								posts = NewResponseTranslater
										.getPosts(response);
								setUpView();
							} else {
								btnRetry.setVisibility(View.VISIBLE);
								prBar.setVisibility(View.GONE);
								lvNormal.setVisibility(View.GONE);
							}

						}

						@Override
						public void onFailure(Throwable arg0, String arg1) {
							super.onFailure(arg0, arg1);
							btnRetry.setVisibility(View.VISIBLE);
							prBar.setVisibility(View.GONE);
							lvNormal.setVisibility(View.GONE);
						}
					});
		} else {
			btnRetry.setVisibility(View.VISIBLE);
			prBar.setVisibility(View.GONE);
			lvNormal.setVisibility(View.GONE);

			Toast.makeText(getSherlockActivity(), "Không có kết nối",
					Toast.LENGTH_SHORT).show();
		}
	}

	private void loadMore() {
		if (NewNetworkUtility.checkNetworkState(getSherlockActivity())) {
			isLoading = true;
			footer.setVisibility(View.VISIBLE);
			RestConnector.post("", NewParamBuilder.BuildParams(NewParamBuilder
					.BuildPostData(pageCount + 1)),
					new AsyncHttpResponseHandler() {

						@Override
						public void onSuccess(int arg0, String response) {
							footer.setVisibility(View.GONE);
							if (response == null) {
								Util.showToast("Lỗi kết nối",
										getSherlockActivity(),
										Toast.LENGTH_SHORT);
								isLoading = false;
								return;
							}
							if (NewResponseTranslater.checkSuccess(response)) {
								ArrayList<Post> newPosts = NewResponseTranslater
										.getPosts(response);
								if (newPosts.size()<1){
									isLoading = false;
									isLastPage = true;
									Util.showToast("Không có dữ liệu mới",
											getSherlockActivity(),
											Toast.LENGTH_SHORT);
									return;
								}
								posts.addAll(newPosts);
								adapter.setPostdata(posts);
								adapter.notifyDataSetChanged();
								pageCount++;
								isLoading = false;
							} else {
								isLoading = false;
								isLastPage = true;
								Util.showToast("Không có dữ liệu mới",
										getSherlockActivity(),
										Toast.LENGTH_SHORT);
							}
							super.onSuccess(arg0, response);
						}

						@Override
						public void onFailure(Throwable arg0, String arg1) {
							super.onFailure(arg0, arg1);
							isLoading = false;
							footer.setVisibility(View.GONE);
							Util.showToast("Lỗi kết nối",
									getSherlockActivity(), Toast.LENGTH_SHORT);
						}

					});
		} else {
			footer.setVisibility(View.GONE);
			Util.showToast("Không có kết nối", getSherlockActivity(),
					Toast.LENGTH_SHORT);
		}
	}

	/*public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(getSherlockActivity(),
				requestCode, resultCode, data);

	}*/

}
